#!/usr/bin/env python
# -*- coding: utf-8 -*-

import clutter

class WidgetsArea(clutter.Group):
    def __init__(self, width, height):
        clutter.Group.__init__(self)
        self.width = width
        self.height = height
        #self.back = r = clutter.Rectangle()
        #r.show()
        #r.set_color(clutter.color_from_string("Black"))
        #r.set_opacity(150)
        #r.set_size(width, height)
        #self._raw_add(r)

    def add(self, widget):
        self._raw_add(widget)
        self.update_widgets()

    def update_widgets(self):
        n = 0
        for widget in self.get_children():
            if True: 
            #if widget != self.back:
                offset = 0
                ypos = 0
                n += 1
                nw = self.get_n_children() 
                #nw = self.get_n_children() - 1
                panel_width = int(self.width/float(nw))
                wwidth = widget.get_width()
                wheight = widget.get_height()
                wratio = hratio = 1
                if wwidth > panel_width:
                    wratio = panel_width/float(wwidth)
                else:
                    offset = (panel_width - wwidth)/2
                if wheight > self.height: 
                    hratio = self.height/float(wheight)
                ypos = int((self.height - wheight*(min(hratio,wratio)))/2)

                ratio = min(wratio, hratio)
                widget.set_scale(ratio, ratio)
                calculated_pos = int((n-1)*panel_width+offset)
                widget.set_position(calculated_pos, ypos)

    def _raw_add(self, widget):
        super(clutter.Group, self).add(widget)
